<template>
  <div class="common-layout">
    <el-container style="margin-right: 20px; margin-left: 20px; margin-top: 20px;">
      <el-header style="background-color: white;">
        <div style="float: left; width: 50%; margin-top: 15px;">
          <el-button @click="goBack">发布商品</el-button>
          <el-button @click="getdelteld">批量上架</el-button>
          <el-button @click="getdeltelds">批量下架</el-button>
          <el-button @click="getdeleteds">删除</el-button>
        </div>
        <div style="float: left; width: 50%; margin-top: 15px;">
          <el-checkbox v-model="Searchs.Sellout" @change="gettableData()">已售罄</el-checkbox>
          <el-select
            placeholder="请选择状态"
            size="large"
            style="width: 240px; margin-left: 10px; margin-height: 5px"
            v-model="Searchs.IsShelves"
            @change="gettableData()"
          >
            <el-option label="全部状态" value="" />
            <el-option label="已上架" value="true" />
            <el-option label="已下架" value="false" />
          </el-select>
          <el-input v-model="Searchs.Name" style="width: 240px; margin-left: 10px" placeholder="输入商品名称" />
          <el-button :icon="Search" circle @click="gettableData()" />
        </div>
      </el-header>
      <el-main style="background-color: white; margin-top: 20px;">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" value="" />
          <el-table-column property="name" label="商品名称" width="120" />
          <el-table-column property="typeName" label="商品类型" width="120" />
          <el-table-column property="salesPrice" label="销售价格" width="120" />
          <el-table-column label="实际销量/剩余库存" width="160">
            <template #default="scope">
              <div v-if="scope.$index === editingRowIndex && editingColumn === 'remaining'">
                <el-input v-model="editingInventory" @blur="updateInventory(scope.$index)" @keyup.enter="updateInventory(scope.$index)" style="width: 50px;" />
              </div>
              <div v-else>
                <span>{{ scope.row.actual }}/{{ scope.row.remaining }}</span>
                <el-icon color="#409efc" class="no-inherit pointer-cursor" @click="startEditing(scope.$index, 'remaining')">
                  <edit />
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="排序" width="120">
            <template #default="scope">
              <div v-if="scope.$index === editingRowIndex && editingColumn === 'sort'">
                <el-input v-model="editingSort" @blur="updateSort(scope.$index)" @keyup.enter="updateSort(scope.$index)" style="width: 50px;" />
              </div>
              <div v-else>
                <span>{{ scope.row.dateSort }}</span>
                <el-icon color="#409efc" class="no-inherit pointer-cursor" @click="startEditing(scope.$index, 'sort')">
                  <edit />
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品状态" width="200" property="isShelves">
            <template #default="scope">
              <el-switch
                v-model="scope.row.isShelves"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="已上架"
                inactive-text="已下架"
                @change="updateStatus(scope.row.id)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="400">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row.id)">编辑</el-button>
              <el-button type="primary" link @click="handleEdit(scope.row.id)">复制</el-button>
              <el-button type="primary" link @click="handleEdit(scope.row.id)">投放</el-button>
              <el-button type="primary" link @click="handleEdit(scope.row.id)">适应酒店</el-button>
              <el-button type="primary" link @click="handleEdit(scope.row.id)">同步微信</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <el-dialog
      v-model="dialogVisible"
      title="发布商品"
      width="500"

    >
      <div class="product-types">
        <el-row :gutter="20" v-for="(item, index) in productTypes" :key="index" @click="insertProductType(item.title, item.id)">
          <el-col :span="24">
            <div class="product-type-item">
              <el-icon :class="`${item.icon} pointer-cursor`" :size="30" />
              <div class="description" @click="adddialogVisible = true">
                <h3>{{ item.title }}</h3>
                <p>{{ item.description }}</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  ShoppingBag,
  Coin,
  Refresh,
} from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElTable, ElMessage, ElForm, ElFormItem, ElInput} from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'


const router = useRouter()

const Searchs = ref({
  Sellout: "",
  IsShelves: "",
  Name: ""
})

const insertProductType = (title: any, id: any) => {
  localStorage.setItem("productType", title)
  localStorage.setItem("productTypeId", id)
  router.push("/InsertProductDisplayView")
}

onMounted(() => {
  gettableData()
  getgoodstype()
})

const tableData = ref<any[]>([])

const gettableData = () => {
  axios.get('https://localhost:44392/api/app/product-display-services/products', {
    params: {
      Sellout: Searchs.value.Sellout,
      IsShelves: Searchs.value.IsShelves,
      Name: Searchs.value.Name
    }
  }).then(res => {
    tableData.value = res.data.data
  })
}

const editingRowIndex = ref(-1)
const editingColumn = ref('')
const editingPrice = ref(0)
const editingInventory = ref(0)
const editingSort = ref(0)

const startEditing = (index: number, column: string) => {
  editingRowIndex.value = index
  editingColumn.value = column
  if (column === 'remaining') {
    editingInventory.value = tableData.value[index].remaining
  } else if (column === 'sort') {
    editingSort.value = tableData.value[index].dateSort
  }
}

const updateInventory = (index: number) => {
  // 这里可以添加更新库存的逻辑
  tableData.value[index].remaining = editingInventory.value
const stock=editingInventory.value
  axios.put("https://localhost:44392/UpdateStockAsync",{
    
      id:tableData.value[index].id,
      stock:stock
   
  }, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(res => {
    if(res.data.isSuc){
      editingRowIndex.value = -1;
      editingColumn.value = '';
      ElMessage.success("更新成功")

       // 更新 tableData 中的数据
      tableData.value[index].remaining = stock;
      
    }else{
      ElMessage.error(res.data.msg)
       // 更新 tableData 中的数据
      tableData.value[index].remaining = stock;
      editingRowIndex.value = -1;
      editingColumn.value = '';
    }
  })
}

const updateSort = (index: number) => {
  // 这里可以添加更新排序的逻辑
  tableData.value[index].dateSort = editingSort.value
   axios.put("https://localhost:44392/GetProductByKeywordAsync",{
    id:tableData.value[index].id,
    sorts:editingSort.value
  }, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(res => {
    if(res.data.isSuc){
      editingRowIndex.value= -1;
      editingColumn.value = ''
      ElMessage.success("更新成功")
      gettableData()
    }else{
      ElMessage.error(res.data.msg)
    }
  })
}

const goBack = () => {
  dialogVisible.value = true
}

const dialogVisible = ref(false)
const productTypes = ref([
  {
    icon: 'shopping-bag',
    title: "",
    description: '普通商品，需商户线下核销，例如：酒店豪华自助餐',
    id: ""
  },
  {
    icon: 'Coin',
    title: "",
    description: '顾客在买单时可以抵扣等值的现金，不可继续用来购买现金券',
    id: ""
  },
  {
    icon: 'Refresh',
    title: "",
    description: '顾客可以多次消费，如10次游泳服务',
    id: ""
  }
])

const adddialogVisible = ref(false)

const updateStatus = (Id: string) => {
  console.log('updateStatus called with Id:', Id); // 添加调试信息
  
debugger
  axios.put(`https://localhost:44392/GetProductByCategoryAsync`, {
    Id:Id
  }).then(res => {
    if (res.data.isSuc) {
      ElMessage.success("更新成功")
      gettableData()
    } else {
      ElMessage.error("更新失败")
    }
  })
}

const getgoodstype = () => {
  axios.get("https://localhost:44392/api/app/add-goods-type-services/goods-show").then(res => {
    res.data.data.forEach((item:any, index:any) => {
      if (productTypes.value[index]) {
        productTypes.value[index].title = item.typeName
        productTypes.value[index].id = item.id
      }
    })
  }).catch(error => {
    console.error('获取商品类型失败:', error)
  })
}

const getbyid = ref<any[]>([])

const handleSelectionChange = (selection: any[]) => {
  getbyid.value = selection
}

const getdelteld = () => {
  if (getbyid.value.length == 0) {
    ElMessage.error('请选择要上架的商品');
    return
  }
  const ids = getbyid.value.map(row => row.id)

  axios.put("https://localhost:44392/api/app/product-display-services/loading-unloadingt", ids).then(res => {
    if (res.data.isSuc) {
      ElMessage.success("上架成功")
      gettableData()
    } else {
      ElMessage.error("上架失败")
    }
  })
}

const getdeltelds = () => {
  if (getbyid.value.length == 0) {
    ElMessage.error('请选择要上架的商品');
    return
  }
  const ids = getbyid.value.map(row => row.id)

  axios.put("https://localhost:44392/api/app/product-display-services/loading-unloadingt", ids).then(res => {
    if (res.data.isSuc) {
      ElMessage.success("下架成功")
      gettableData()
    } else {
      ElMessage.error("下架失败")
    }
  })
}

const getdeleteds = () => {
  if (getbyid.value.length == 0) {
    ElMessage.error('请选择要删除的商品');
    return
  }
  const ids = getbyid.value.map(row => row.id)
  console.log(ids)

  axios.put("https://localhost:44392/api/app/product-display-services/delete-product", ids).then(res => {
    if (res.data.isSuc) {
      ElMessage.success("删除成功")
      gettableData()
    } else {
      ElMessage.error("删除失败")
    }
  })
}

const handleEdit = (id: any) => {
  localStorage.setItem("productId", id)
  router.push("/UpdateProductDisplayView")
}
</script>

<style scoped>
.pointer-cursor {
  cursor: pointer;
}

.product-types {
  padding: 20px;
}

.product-type-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  text-align: left;
  cursor: pointer;
  width: 400px; /* 确保每个商品类型占据整个 el-col 的宽度 */
}

.product-type-item .el-icon {
  margin-bottom: 10px;
  background-color: transparent;
  transition: background-color 0.3s ease;
}

.product-type-item .el-icon:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.description {
  display: flex;
  flex-direction: column;
}

.description h3 {
  font-size: 16px;
  margin: 0;
}

.description p {
  font-size: 14px;
  color: #909399;
}
</style>